//
//  HMStatusViewModel.swift
//  sinaweibo
//
//  Created by WGP on 16/4/13.
//  Copyright © 2016年 WGP. All rights reserved.
//

import UIKit

import SDWebImage

class HMStatusViewModel: NSObject {
    
//    不要同时出现2个加在微博的请求
    private var loadStatus: Bool = false
    
//    单例
    static let sharedInstance: HMStatusViewModel = HMStatusViewModel()
    
    ///加载本地数据
    private func loadLocalStatuses()
    {
        let path = NSBundle.mainBundle().pathForResource("statuses", ofType: "json")!
        let data  = NSData(contentsOfFile: path)
        
//        函数抛出异常在函数后面有throws,表示这段可能会有异常,如果我们处理这个异常,程序不会挂掉的,不处理就会挂掉
//        try!: 强制try,有异常不处理,如果真的有异常程序就会挂掉
//        do try catch: 处理异常,如果出现异常就会走catch这个代码快,程序不会挂掉
        do
        {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]
            HMPrint("Json:\(json)")
        }
        catch let error as NSError
        {
            HMPrint("JSon序列化异常:\(error)")
        }
        
    }
    
    
///加载微博数据
    func loadStatus(since_id: Int64, max_id: Int64,  loadStatusFinished:(statuses: [HMStatus]?,error: NSError?)->())
    {
        
//        判断是否有人在加载微博数据
        if loadStatus == true
        {
            HMPrint("有人在加载微博数据!")
            let error = HMNetworkErrorEnum.RepeatLoadStatus.error()
//            把加载失败的原因传回去
            loadStatusFinished(statuses: nil, error: error)
            return
        }
        
//        将加载的状态改成true,表示有人在加载
        loadStatus = true
        
//        1.url
//        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        
////        2.参数
//        var parameters: [String:AnyObject] =
//        [
//            "access_token":HMUserAccountViewModel.sharedInstance.userAccount!.access_token!
//        ]
//        
////        将since_id,max_id拼接到参数里
//        if since_id > 0
//        {
//            parameters["since_id"] = NSNumber(longLong: since_id)
//            
//        } else if max_id > 0
//        {
////            返回小于max_id的微博数据,不需要等于
//            parameters["max_id"] = NSNumber(longLong: max_id-1)
//        }
        
//        3.发送请求
//        HMNetWorkTool.sharedInstance.GET(urlStr, parameters:parameters, progress: nil, success: { (task, responseObject) -> Void in
//            
////            加在玩数据后不管有没有家在到数据,都要更改加载数据的状态
//            self.loadStatus = false
//            
//            if let dict = responseObject as? [String:AnyObject],let statusDict = dict["statuses"] as? [[String: AnyObject]]
//            {
//                var statusM: [HMStatus] = []
//                
//                for dict in statusDict
//                {
//                    let status = HMStatus(dict: dict)
//                    
//                    //                    将模型添加到数组中
//                    statusM.append(status)
//                }
//                
//                //                缓存图片
//                self.cacheWebImage(statusM, loadStatusFinished: loadStatusFinished)
//                
//            }
//            
//            }) { (task, error) -> Void in
//                 self.loadStatus = false
//               loadStatusFinished( statuses: nil,error: error)
//        }
        
        HMStatusDAL.sharedDAL.loadStatus(since_id, max_id: max_id) { (status, error) -> () in
            
            self.loadStatus = false
            if error != nil
            {
                print("加载数据出错了:\(error)")
                loadStatusFinished(statuses: nil, error: error)
                
                return
            }
            
            var statusModels: [HMStatus] = []
            
            for dict in status!
            {
                let status = HMStatus(dict: dict)
                
                statusModels.append(status)
            }
            
//            缓存图片,将控制器传入的闭包

             self.cacheWebImage(statusModels, loadStatusFinished: loadStatusFinished)
        }
        
    }
    
    ///缓存微博图片
    private func cacheWebImage(statuses: [HMStatus],loadStatusFinished:([HMStatus]?, error: NSError?)->())
    {
//        创建主任务
        let group = dispatch_group_create()
        
        
       for status in statuses
       {
             var downloadURLs: [NSURL]?
            downloadURLs = status.pic_urlsArr
            
            if downloadURLs == nil
            {
                downloadURLs = status.retweeted_status?.pic_urlsArr
            
            }
        
            if let urls = downloadURLs
            {
                if urls.count == 1
                {
                    let url = urls.first!
                    
                    dispatch_group_enter(group)
                    
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in
                        
//                        记得要关掉group
                        dispatch_group_leave(group)
                        
                        if error != nil
                        {
                            HMPrint("系在图片失败:\(error)")
                            return
                        }
                        
                      
                    })
                }
            }
        }
        
//        监听所有微博下载图片完成
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
//         HMPrint("SD下载所有的图片完成")
            
//            下载所有的图片完成后,回调控制器,控制器会拿到数据,然后刷新界面
             loadStatusFinished(statuses,error: nil)
        }
    }
    
//    MARK: - 发微博
    ///text:要发布的微博的内容
    func sendStatus(text: String, image: UIImage?, sendStatusCallBack:(error: NSError?)->())
    {
        guard let access_token = HMUserAccountViewModel.sharedInstance.userAccount?.access_token else
        {
            let error = HMNetworkErrorEnum.AccessTokenEmpty.error()
            sendStatusCallBack(error: error)
            return
        }
        
        let parameters =
        [
            "access_token" : access_token,
            "status":text
        ]
        
        if image == nil
        {
            let urlString = "https://api.weibo.com/2/statuses/update.json"
            
            //        发送请求
            HMNetWorkTool.sharedInstance.POST(urlString, parameters: parameters, progress: nil, success: { (task, _) -> Void in
                //            发布成功
                sendStatusCallBack(error: nil)
                }) { (task, error) -> Void in
                    sendStatusCallBack(error: error)
            }
        }
        else
        {
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            HMNetWorkTool.sharedInstance.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                
                let data = UIImagePNGRepresentation(image!)!
                
                // 上传图片
                // data: NSData: 要上传的二进制
                // name: API文档指定的上传参数
                // fileName: 上传后保存在服务器的名称,看API，如果API没有指定,可以不写
                // mimeType: 上传二进制的类型 image,  image/png, image/jpeg, image/gif
                
                formData.appendPartWithFileData(data, name: "pic", fileName: "", mimeType: "image/png")
                
                }, progress: nil, success: { (_, responseObject) -> Void in
                    
                    sendStatusCallBack(error: nil)
                    
                }, failure: { (_, error) -> Void in
                    
                    sendStatusCallBack(error: error)
            })
        }

    }

}









